﻿using AssistCore;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Helper
{
    public partial class ExamHelper : CCWin.Skin_Mac
    {
        public ExamHelper()
        {
            InitializeComponent();
        }
        IntPtr gameHwnd = IntPtr.Zero;
        Thread examThread = null;
        TencentImageCore imageCore = null;

        private void btn_start_Click(object sender, EventArgs e)
        {
            if (examThread != null && examThread.IsAlive)
            {
                StopExam();
            }
            else
            {
                examThread = new Thread(StartExam);
                examThread.Start();
                btn_start.Text = "停止考试(Home)";
            }
        }

        private void ExamHelper_Shown(object sender, EventArgs e)
        {
            var ret = ExamTiKu.Load(Properties.HelpResource.dict);
            if (!ret)
            {
                MessageBox.Show("题库载入失败，请确认启动目录data.jx3文件！", "", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                this.Close();
                return;
            }
            imageCore = new TencentImageCore("1251084064", "AKIDQr7B6rfr57yd7PIQ9g7R4WmqiNqCLWTK", "oQSO9iGj06zgBUmvsdCZkkYQFsLeopqf");
            //启动时先进行一次测试识别。
            var filePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".png");
            Properties.HelpResource.testocr.Save(filePath);
            var text = imageCore.OCRGeneral(filePath);
            Console.WriteLine(text);
            File.Delete(filePath);
            Win32Core.RegisterHotKey(this.Handle, 100, 0, (int)Keys.Home);
        }
        protected override void WndProc(ref Message m)
        {
            const int WM_HOTKEY = 0x0312;
            switch (m.Msg)
            {
                case WM_HOTKEY:
                    HandleHotkey(m);
                    break;
            }
            base.WndProc(ref m);
        }
        private void HandleHotkey(Message m)
        {
            switch (m.WParam.ToInt32())
            {
                case 100:
                    {
                        btn_start.PerformClick();
                        break;
                    }
            }
        }

        private void ExamHelper_FormClosed(object sender, FormClosedEventArgs e)
        {
            Win32Core.UnregisterHotKey(this.Handle, 100);
        }

        private void StartExam()
        {
            var p = new Point();
            Win32Core.GetCursorPos(out p);
            gameHwnd = Win32Core.WindowFromPoint(p);
            Win32Core.SetForegroundWindow(gameHwnd);
            Thread.Sleep(1000);
            CDD.DDContext.key((int)DDKeys.F, 1);
            CDD.DDContext.key((int)DDKeys.F, 2);
            Thread.Sleep(500);

            Bitmap lastBp = null;
            int maxTryCount = 0;
            for (var i = 0; i < 10; i++)
            {
                Bitmap bp = new Bitmap(610, 292);
                Graphics g = Graphics.FromImage(bp);
                copy: g.CopyFromScreen(new Point(70, 277), new Point(0, 0), bp.Size);
                if (ImageCore.IsSimilarImage(bp, lastBp, 500, 100, 0.2f))
                {
                    if (maxTryCount++ < 50)
                    {
                        goto copy;
                    }
                    else
                    {
                        MessageBox.Show("尝试次数已达到上限，线程终止。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                        StopExam();
                        return;
                    }
                }
                else
                {
                    lastBp = (Bitmap)bp.Clone();
                }
                var filePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".png");
                Console.WriteLine(filePath);
                bp.Save(filePath, ImageFormat.Png);
                var ret = imageCore.OCRGeneral(filePath);
                if (ret.code != 0 || ret.data.items.Count < 1)
                {
                    MessageBox.Show("OCR识别失败：" + ret.message.ToString(), ret.code.ToString(), MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    return;
                }
                var questionOCR = ret.data.items[0].itemstring.ToString().Replace("单选题：", "").Replace("单选题:", "");
                var answerOCRArray = new string[Math.Min(ret.data.items.Count - 1, 4)];
                for (int j = ret.data.items.Count - 1, k = 0; j > 0; j--, k++)
                {
                    if (k < 4)
                    {
                        answerOCRArray[(answerOCRArray.Length - 1) - k] = ret.data.items[j].itemstring;
                    }
                    else
                    {
                        questionOCR += ret.data.items[j].itemstring;
                    }
                }
                Console.WriteLine("识别问题：" + questionOCR);
                for (var j = 0; j < answerOCRArray.Length; j++)
                {
                    Console.WriteLine("识别答案：" + answerOCRArray[j]);
                }
                var questionSearch = ExamTiKu.GetSimilarTiMu(questionOCR);
                Console.WriteLine("搜索后问题：" + questionSearch);
                int index = 0;
                var answerSearch = ExamTiKu.GetAnswer(questionSearch, answerOCRArray, out index);
                Console.WriteLine("得到答案，选择：{0}，位置：{1}", answerSearch, index);

                var answerPos = new Point[] {
                        new Point(115,400),
                        new Point(115,435),
                        new Point(115,475),
                        new Point(115,510)
                    };
                Console.WriteLine("移动鼠标到：{0},{1}", answerPos[index].X, answerPos[index].Y);
                CDD.DDContext.mov(answerPos[index].X, answerPos[index].Y);
                Thread.Sleep(10);
                CDD.DDContext.btn(1);
                CDD.DDContext.btn(2);
                CDD.DDContext.mov(480, 590);
                Thread.Sleep(10);
                CDD.DDContext.btn(1);
                CDD.DDContext.btn(2);

                bp.Dispose();
                g.Dispose();
                //File.Delete(filePath);
            }
            return;
            CDD.DDContext.mov(907, 374);
            CDD.DDContext.btn(1);
            CDD.DDContext.btn(2);
            StopExam();
        }
        private void StopExam()
        {
            Action action = () =>
            {
                btn_start.Text = "开始考试(Home)";
            };
            if (btn_start.InvokeRequired)
            {
                btn_start.Invoke(action);
            }
            else
            {
                action();
            }
            examThread.Abort();
        }
    }
}
